if (!is.loaded("mpi_initialize")) {
    library("Rmpi")
}

cat("mpi comm size is ", mpi.comm.size(), "\n")

mpi.spawn.Rslaves(nslaves=8)

sz = mpi.universe.size()
cat("mpi universe size is", sz, "\n")
cat("mpi comm size is ", mpi.comm.size(), "\n")

.Last <- function() {
    if (is.loaded("mpi_initialize")) {
        if (mpi.comm.size(1) > 0) {
            print("Pleaes use mpi.close.Rslaves() to close slaves.")
            mpi.close.Rslaves()
        }
        print("Please use mpi.quit() to quit R")
        .Call("mpi_finalize")
    }
}

mpi.remote.exec(paste("I am", mpi.comm.rank(), "of", mpi.comm.size()))
mpi.close.Rslaves()
mpi.quit()
